package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.RestResponse;
import com.alvis.media.domain.other.KeyValue;
import com.alvis.media.domain.User;
import com.alvis.media.domain.UserEventLog;
import com.alvis.media.domain.enums.UserStatusEnum;
import com.alvis.media.service.AuthenticationService;
import com.alvis.media.service.UserEventLogService;
import com.alvis.media.service.UserService;
import com.alvis.media.utility.DateTimeUtil;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.admin.user.*;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 后台普通用户列表
 */

@RestController("AdminUserController")
@RequestMapping(value = "/api/admin/user")
@AllArgsConstructor
public class UserController extends BaseApiController {
    /**
     * 普通用户Service
     */
    private final UserService userService;
    /**
     * 普通用户日志Service
     */
    private final UserEventLogService userEventLogService;
    /**
     * 权限Service
     */
    private final AuthenticationService authenticationService;

    /**
     * 查询用户列表方法
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserResponseVM>> pageList(@RequestBody UserPageRequestVM model) {
        PageInfo<User> pageInfo=userService.userPage(model);
        PageInfo<UserResponseVM> page=PageInfoHelper.copyMap(pageInfo,d->UserResponseVM.from(d));

        return RestResponse.ok(page);
    }


    @RequestMapping(value = "/event/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserEventLogVM>> eventPageList(@RequestBody UserEventPageRequestVM model) {
        PageInfo<UserEventLog> pageInfo=userEventLogService.page(model);
        PageInfo<UserEventLogVM> page=PageInfoHelper.copyMap(pageInfo,d-> {
            UserEventLogVM vm=modelMapper.map(d,UserEventLogVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(d.getCreateTime()));
            return vm;
        });

        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> select(@PathVariable Integer id) {
        User user=userService.getUserById(id);
        UserResponseVM userVm=UserResponseVM.from(user);

        return RestResponse.ok(userVm);
    }

    @RequestMapping(value = "/current", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> current() {
        User user = getCurrentUser();
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }


    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<User> edit(@RequestBody @Valid UserCreateVM model) {
        if (model.getId()==null){
            User existUser=userService.getUserByUserName(model.getUserName());
            if (null!=existUser){
                return new RestResponse<>(2,"用户已存在");
            }
            if (StringUtils.isBlank(model.getPassword())){
                return new RestResponse<>(3,"密码不能为空");
            }
        }
        if (StringUtils.isBlank(model.getBirthDay())){
            model.setBirthDay(null);
        }
        User user=modelMapper.map(model,User.class);

        if (model.getId()==null){
            String encodePwd=authenticationService.pwdEncode(model.getPassword());
            user.setPassword(encodePwd);
            user.setUserUuid(UUID.randomUUID().toString());
            user.setUserName(model.getUserName());
            user.setRealName(model.getRealName());
            user.setUserLevel(model.getUserLevel());
            user.setCreateTime(new Date());
            user.setLastActiveTime(new Date());
            user.setDeleted(false);
            userService.insertByFilter(user);
        }else {
            if (!StringUtils.isBlank(model.getPassword())){
                String encodePwd =authenticationService.pwdEncode(model.getPassword());
                user.setPassword(encodePwd);
            }
            user.setModifyTime(new Date());
            userService.updateByIdFilter(user);
        }

        return RestResponse.ok(user);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public RestResponse update(@RequestBody @Valid UserUpdateVM model) {
        User user=userService.selectById(getCurrentUser().getId());
        modelMapper.map(model,user);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);

        return RestResponse.ok();
    }

    /**
     * 启用/禁用代码
     * @param id 要启用/禁用的某条用户记录的主键（用户编号）值 修改T_USER表中status 1-启用  2-禁用
     * @return 响应对应的JSON数据给页面
     */
    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserStatusEnum userStatusEnum=UserStatusEnum.fromCode(user.getStatus());
        Integer newStatus=userStatusEnum==UserStatusEnum.Enable ? UserStatusEnum.Disable.getCode() : UserStatusEnum.Enable.getCode();
        user.setStatus(newStatus);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);

        return RestResponse.ok(newStatus);
    }

    /**
     * 删除用户信息
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        user.setDeleted(true);
        userService.updateByIdFilter(user);

        return RestResponse.ok();
    }


    @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName) {
        List<KeyValue> keyValues=userService.selectByUserName(userName);

        return RestResponse.ok(keyValues);
    }



    @RequestMapping(value = "/getUserDetailByUserId/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> getUserDetailByUserId(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }
}
